package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.util.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public List<Cart> listCart(Object...item) {
        List<Cart> list = new ArrayList<>();
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            list = dao.listCart(item);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(Cart cart)  {
        CartDao dao = new CartDaoImpl();
        int result = 0;
        try {
            DBUtil.beginTransaction();
            result = dao.saveCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }finally {
                DBUtil.close();
            }
        }
        return result;
    }

    @Override
    public int updateCart(Cart cart) {
        CartDao dao = new CartDaoImpl();
        int result = 0;
        try {
            DBUtil.beginTransaction();
            result = dao.updateCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }finally {
                DBUtil.close();
            }
        }
        return result;
    }

    @Override
    public int removeCart(Object...item)  {
        CartDao dao = new CartDaoImpl();
        int result = 0;
        try {
            DBUtil.beginTransaction();
            result = dao.removeCart(item);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                DBUtil.close();
            }
        }
        return result;
    }
}
